<template>
    <view class="register-container">
        <!-- 头部导航 -->
        <view class="header" :style="{ paddingTop: (statusBarHeight + 10) + 'px' }">
            <button class="back-btn" @click="goBack">
                <view class="back-icon-wrapper">
                    <text class="back-icon">‹</text>
                </view>
            </button>
            <button class="help-btn" @click="showHelp">
                <view class="help-icon-wrapper">
                    <text class="help-icon">?</text>
                </view>
            </button>
        </view>

        <!-- 主要内容 -->
        <view class="main-content">
            <!-- 标题 -->
            <view class="title-section">
                <text class="page-title">创建您的帐户</text>
            </view>

            <!-- 表单区域 -->
            <view class="form-section">
                <!-- 手机号输入 -->
                <view class="form-item">
                    <view class="input-container">
                        <input 
                            class="input" 
                            type="number" 
                            placeholder="手机号" 
                            v-model="formData.mobile"
                            maxlength="11" 
                        />
                        <text class="input-label">手机号</text>
                    </view>
                </view>

                <!-- 昵称输入 -->
                <view class="form-item">
                    <view class="input-container">
                        <input 
                            class="input" 
                            type="text" 
                            placeholder="昵称" 
                            v-model="formData.nickname"
                            maxlength="20" 
                        />
                        <text class="input-label">昵称</text>
                    </view>
                </view>

                <!-- 出生年月日 -->
                <view class="form-item">
                    <view class="input-container" @click="showDatePicker">
                        <view class="picker-input">
                            {{ formData.birthday || '出生年月日' }}
                        </view>
                        <text class="input-label">出生年月日</text>
                    </view>
                </view>

                <!-- 地址输入 -->
                <view class="form-item">
                    <view class="input-container">
                        <input 
                            class="input" 
                            type="text" 
                            placeholder="地址" 
                            v-model="formData.address"
                        />
                        <text class="input-label">地址</text>
                    </view>
                </view>
            </view>

            <!-- 底部区域 -->
            <view class="bottom-section">
                <!-- 注册按钮 -->
                <button 
                    class="primary-btn" 
                    :disabled="!canRegister || registerLoading"
                    @click="handleRegister"
                >
                    {{ registerLoading ? '创建中...' : '创建帐户' }}
                </button>

                <!-- 隐私政策 -->
                <view class="privacy-text">
                    <text>继续即表示您同意我们的</text>
                    <text class="privacy-link" @click="showTerms">服务条款</text>
                    <text>和</text>
                    <text class="privacy-link" @click="showPrivacy">隐私政策</text>
                    <text>。</text>
                </view>
            </view>
        </view>

        <!-- 验证码弹窗 -->
        <view class="code-modal" v-if="showCodeModal" @click="hideCodeModal">
            <view class="code-modal-content" @click.stop>
                <view class="code-modal-header">
                    <text class="code-modal-title">验证手机号</text>
                    <button class="code-modal-close" @click="hideCodeModal">×</button>
                </view>
                <view class="code-modal-body">
                    <text class="code-tip">验证码已发送至 {{ formData.mobile }}</text>
                    <view class="code-input-container">
                        <input 
                            class="code-input" 
                            type="number" 
                            placeholder="请输入验证码" 
                            v-model="formData.code"
                            maxlength="6"
                        />
                        <button 
                            class="send-code-btn"
                            :disabled="codeCountdown > 0"
                            @click="sendSmsCode"
                        >
                            {{ codeCountdown > 0 ? `${codeCountdown}s` : '重新发送' }}
                        </button>
                    </view>
                    <button class="verify-btn" @click="verifyCode" :disabled="!formData.code">
                        验证并注册
                    </button>
                </view>
            </view>
        </view>

        <!-- 日期选择器 -->
        <view class="date-picker-modal" v-if="showDateModal" @click="hideDatePicker">
            <view class="date-picker-content" @click.stop>
                <view class="date-picker-header">
                    <button class="date-picker-cancel" @click="hideDatePicker">取消</button>
                    <text class="date-picker-title">选择出生日期</text>
                    <button class="date-picker-confirm" @click="confirmDate">确定</button>
                </view>
                <picker-view class="date-picker-view" :value="pickerValue" @change="onPickerChange">
                    <picker-view-column>
                        <view v-for="(year, index) in years" :key="index" class="picker-item">
                            {{ year }}年
                        </view>
                    </picker-view-column>
                    <picker-view-column>
                        <view v-for="(month, index) in months" :key="index" class="picker-item">
                            {{ month }}月
                        </view>
                    </picker-view-column>
                    <picker-view-column>
                        <view v-for="(day, index) in days" :key="index" class="picker-item">
                            {{ day }}日
                        </view>
                    </picker-view-column>
                </picker-view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      registerLoading: false,
      codeCountdown: 0,
      showCodeModal: false,
      showDateModal: false,
      pickerValue: [0, 0, 0],
      years: [],
      months: [],
      days: [],
      formData: {
        mobile: '',
        code: '',
        nickname: '',
        birthday: '',
        address: ''
      }
    }
  },
  
  computed: {
    canRegister() {
      const mobileRegex = /^1[3-9]\d{9}$/;
      return this.formData.mobile && 
             mobileRegex.test(this.formData.mobile) &&
             this.formData.nickname;
    }
  },
  
  onLoad(options) {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 20;
    
    // 初始化日期选择器数据
    this.initDatePicker();
  },
  
  methods: {
    // 返回
    goBack() {
      uni.navigateBack();
    },
    
    // 显示帮助
    showHelp() {
      uni.showToast({ title: '如需帮助，请联系客服', icon: 'none' });
    },
    
    // 初始化日期选择器
    initDatePicker() {
      const currentYear = new Date().getFullYear();
      
      // 生成年份数组（1950-当前年份）
      this.years = [];
      for (let i = 1950; i <= currentYear; i++) {
        this.years.push(i);
      }
      
      // 生成月份数组
      this.months = [];
      for (let i = 1; i <= 12; i++) {
        this.months.push(i);
      }
      
      // 生成日期数组
      this.updateDays();
      
      // 设置默认值为1990年1月1日
      this.pickerValue = [40, 0, 0]; // 1990年在数组中的索引
    },
    
    // 更新日期数组
    updateDays() {
      const year = this.years[this.pickerValue[0]] || 2000;
      const month = this.months[this.pickerValue[1]] || 1;
      const daysInMonth = new Date(year, month, 0).getDate();
      
      this.days = [];
      for (let i = 1; i <= daysInMonth; i++) {
        this.days.push(i);
      }
    },
    
    // 显示日期选择器
    showDatePicker() {
      this.showDateModal = true;
    },
    
    // 隐藏日期选择器
    hideDatePicker() {
      this.showDateModal = false;
    },
    
    // 选择器值改变
    onPickerChange(e) {
      this.pickerValue = e.detail.value;
      this.updateDays();
      
      // 如果当前选择的日期超出了新月份的天数，调整到最后一天
      if (this.pickerValue[2] >= this.days.length) {
        this.pickerValue[2] = this.days.length - 1;
      }
    },
    
    // 确认日期选择
    confirmDate() {
      const year = this.years[this.pickerValue[0]];
      const month = String(this.months[this.pickerValue[1]]).padStart(2, '0');
      const day = String(this.days[this.pickerValue[2]]).padStart(2, '0');
      
      this.formData.birthday = `${year}-${month}-${day}`;
      this.hideDatePicker();
    },
    
    // 发送短信验证码
    async sendSmsCode() {
      if (!this.formData.mobile) {
        uni.showToast({ title: '请输入手机号', icon: 'none' });
        return;
      }
      
      const mobileRegex = /^1[3-9]\d{9}$/;
      if (!mobileRegex.test(this.formData.mobile)) {
        uni.showToast({ title: '手机号格式错误', icon: 'none' });
        return;
      }
      
      try {
        const result = await uniCloud.callFunction({
          name: 'send-sms',
          data: {
            mobile: this.formData.mobile,
            type: 'register'
          }
        });
        
        if (result.result.code === 200) {
          uni.showToast({ title: '验证码发送成功', icon: 'success' });
          this.startCountdown();
          
          // 开发环境下显示验证码
          if (result.result.data.code) {
            console.log('验证码：', result.result.data.code);
            this.formData.code = result.result.data.code;
          }
        } else {
          uni.showToast({ title: result.result.message, icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '发送失败，请重试', icon: 'none' });
      }
    },
    
    // 开始倒计时
    startCountdown() {
      this.codeCountdown = 60;
      const timer = setInterval(() => {
        this.codeCountdown--;
        if (this.codeCountdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    
    // 显示服务条款
    showTerms() {
      uni.navigateTo({
        url: '/pages/privacy/privacy?type=terms'
      });
    },
    
    // 显示隐私政策
    showPrivacy() {
      uni.navigateTo({
        url: '/pages/privacy/privacy?type=privacy'
      });
    },
    
    // 注册处理（先验证手机号再发送验证码）
    async handleRegister() {
      if (!this.canRegister) {
        uni.showToast({ title: '请完善必填信息', icon: 'none' });
        return;
      }
      
      // 发送验证码并显示验证弹窗
      await this.sendSmsCode();
      if (this.codeCountdown > 0) {
        this.showCodeModal = true;
      }
    },
    
    // 隐藏验证码弹窗
    hideCodeModal() {
      this.showCodeModal = false;
      this.formData.code = '';
    },
    
    // 验证码验证并完成注册
    async verifyCode() {
      if (!this.formData.code) {
        uni.showToast({ title: '请输入验证码', icon: 'none' });
        return;
      }
      
      this.registerLoading = true;
      
      try {
        // 构建注册数据
        const registerData = {
          mobile: this.formData.mobile,
          code: this.formData.code,
          nickname: this.formData.nickname,
          birthday: this.formData.birthday,
          address: this.formData.address
        };
        
        const result = await uniCloud.callFunction({
          name: 'user-register',
          data: registerData
        });
        
        if (result.result.code === 200) {
          uni.showToast({ title: '注册成功', icon: 'success' });
          this.hideCodeModal();
          
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/login/login' });
          }, 1500);
        } else {
          uni.showToast({ title: result.result.message, icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '注册失败，请重试', icon: 'none' });
      } finally {
        this.registerLoading = false;
      }
    },

  }
}
</script>

<style scoped>
/* 主容器 */
.register-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  min-height: max(600px, 100vh);
  background-color: #ffffff;
  font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

/* 头部导航 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  padding-top: 10rpx;
}

.back-btn,
.help-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  outline: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.back-btn:active,
.help-btn:active {
  transform: scale(0.95);
  opacity: 0.7;
}

.back-icon-wrapper,
.help-icon-wrapper {
  width: 88rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f3f4f6;
  transition: all 0.2s ease;
}

.back-btn:hover .back-icon-wrapper,
.help-btn:hover .help-icon-wrapper {
  background-color: #e5e7eb;
}

.back-icon,
.help-icon {
  font-size: 48rpx;
  color: #6b7280;
  font-weight: 600;
  line-height: 1;
}

.back-icon {
  margin-left: -4rpx;
}

/* 主要内容 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0 48rpx;
}

/* 标题区域 */
.title-section {
  margin-bottom: 64rpx;
}

.page-title {
  display: block;
  font-size: 48rpx;
  font-weight: 700;
  color: #111827;
  letter-spacing: -0.025em;
}

/* 表单区域 */
.form-section {
  margin-bottom: 48rpx;
}

.form-item {
  margin-bottom: 48rpx;
}

/* 输入容器 */
.input-container {
  position: relative;
}

.input,
.picker-input {
  width: 100%;
  height: 112rpx;
  padding: 32rpx;
  border: none;
  border-radius: 16rpx;
  background-color: #f3f4f6;
  font-size: 32rpx;
  color: #111827;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.input::placeholder {
  color: #9ca3af;
}

.input:focus {
  background-color: #ffffff;
  outline: none;
  box-shadow: 0 0 0 4rpx rgba(14, 165, 233, 0.1);
}

.picker-input {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #111827;
}

.input-label {
  position: absolute;
  left: 32rpx;
  top: -16rpx;
  background-color: #ffffff;
  padding: 0 8rpx;
  font-size: 24rpx;
  color: #6b7280;
  pointer-events: none;
}

/* 底部区域 */
.bottom-section {
  margin-top: auto;
  padding-bottom: 48rpx;
}

/* 主要按钮 */
.primary-btn {
  width: 100%;
  height: 112rpx;
  background-color: #0284c7;
  color: #ffffff;
  border: none;
  border-radius: 16rpx;
  font-size: 36rpx;
  font-weight: 700;
  margin-bottom: 32rpx;
  transition: all 0.3s ease;
}

.primary-btn:hover {
  background-color: #0369a1;
}

.primary-btn[disabled] {
  background-color: #d1d5db;
  color: #9ca3af;
}

/* 隐私政策文本 */
.privacy-text {
  text-align: center;
  font-size: 24rpx;
  color: #9ca3af;
  line-height: 1.5;
  padding: 0 32rpx;
}

.privacy-link {
  color: #0284c7;
  font-weight: 600;
  text-decoration: none;
  transition: color 0.3s ease;
}

.privacy-link:hover {
  text-decoration: underline;
}

/* 验证码弹窗 */
.code-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.code-modal-content {
  background-color: #ffffff;
  border-radius: 24rpx;
  margin: 48rpx;
  max-width: 640rpx;
  width: 100%;
  max-height: 80vh;
  overflow: hidden;
}

.code-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 48rpx 48rpx 24rpx;
  border-bottom: 1px solid #f3f4f6;
}

.code-modal-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #111827;
}

.code-modal-close {
  background: none;
  border: none;
  font-size: 48rpx;
  color: #6b7280;
  cursor: pointer;
  padding: 0;
  line-height: 1;
}

.code-modal-body {
  padding: 48rpx;
}

.code-tip {
  display: block;
  font-size: 28rpx;
  color: #6b7280;
  margin-bottom: 48rpx;
  text-align: center;
}

.code-input-container {
  display: flex;
  gap: 24rpx;
  margin-bottom: 48rpx;
}

.code-input {
  flex: 1;
  height: 96rpx;
  padding: 32rpx;
  border: 1px solid #d1d5db;
  border-radius: 16rpx;
  background-color: #ffffff;
  font-size: 32rpx;
  color: #111827;
  text-align: center;
}

.send-code-btn {
  height: 96rpx;
  padding: 0 32rpx;
  background-color: #0284c7;
  color: #ffffff;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  white-space: nowrap;
  flex-shrink: 0;
}

.send-code-btn[disabled] {
  background-color: #d1d5db;
  color: #9ca3af;
}

.verify-btn {
  width: 100%;
  height: 96rpx;
  background-color: #0284c7;
  color: #ffffff;
  border: none;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 700;
}

.verify-btn[disabled] {
  background-color: #d1d5db;
  color: #9ca3af;
}

/* 日期选择器弹窗 */
.date-picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.date-picker-content {
  background-color: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow: hidden;
}

.date-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 48rpx;
  border-bottom: 1px solid #f3f4f6;
}

.date-picker-cancel,
.date-picker-confirm {
  background: none;
  border: none;
  font-size: 32rpx;
  color: #0284c7;
  cursor: pointer;
  padding: 16rpx;
}

.date-picker-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #111827;
}

.date-picker-view {
  height: 520rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  font-size: 32rpx;
  color: #111827;
}
</style>